package top.yoahh.security.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Slf4j
@Component
public class AccessDecisionManagerConfig implements AccessDecisionManager {


    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        Collection<? extends GrantedAuthority> auths = authentication.getAuthorities();
        for (ConfigAttribute configAttribute : collection) {
            log.info("========>该URL需要的权限：{}", configAttribute.getAttribute());
            log.info("========>当前用户拥有的权限：{}", JSON.toJSONString(auths));
			/*
			  如果需要的角色是ROLE_ANONYMOUS，说明当前请求的URL用户登陆后即可访问；
			  如果authentication是UsernamePasswordAuthenticationToken实例，说明当前用户已登录。
			 */
            if ("ROLE_ANONYMOUS".equals(configAttribute.getAttribute()) &&
                    authentication instanceof UsernamePasswordAuthenticationToken) {
                return;
            }
            for (GrantedAuthority authority : auths) {
                if (configAttribute.getAttribute().equals(authority.getAuthority())) {
                    return;
                }
            }
        }
        log.info("========>权限不足");
        throw new AccessDeniedException("权限不足！");

    }

    /**
     * 是否支持校验
     */
    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    /**
     * 是否支持校验
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
